/* service层数据库对接 */
// const { exc, escape } = require('../db/mysql') // 导入数据库操作方法
const User = require('../db/model/user') // 导入sequelize User模型

/**
 * 用户查询
 * @param username 用户名
 * @returns {Promise<unknown>}
 */
const getUserService = async (username) => {
  /*
  // mysql
  username = escape(username)
  // 去掉查询变量的字符串
  // const sql = `select * from user where username='${username}'`
  const sql = `select * from user where username=${username}`
  const results = await exc(sql)
  console.log('用户查询', results)
  return results
  */
  // sequelize
  const results = await User.findAll({
    where: {
      username
    }
  })
  console.log('用户查询', results)
  return results
}
/**
 * 用户数据校验
 * @param username 用户名
 * @param password 密码
 * @returns {Promise<unknown>}
 */
const getUserDataService = async (username, password) => {
  /*
  // mysql
  username = escape(username)
  password = escape(password)
  // 去掉查询变量的字符串
  // const sql = `select * from user where username='${username}'`
  const sql = `select * from user where username=${username} and password=${password}`
  const results = await exc(sql)
  console.log('账号密码校验', results)
  return results
  */
  // sequelize
  const results = await User.findAll({
    where: {
      username,
      password
    }
  })
  console.log('账号密码校验', results)
  return results
}
/**
 * 用户注册
 * @param data req.body 数据
 * @returns {Promise<unknown>}
 */
const registerUserService = async ({ username, password, gender }) => {
  /*
  // mysql
  const sql = `insert into user (username, password, gender) values ('${username}','${password}', '${gender}')`
  const results = await exc(sql)
  console.log('用户注册', results)
  return results
  */
  // sequelize
  const results = await User.create({
    username,
    password,
    gender
  })
  console.log('用户注册', results)
  return results.dataValues
}

module.exports = {
  getUserService,
  registerUserService,
  getUserDataService
}
